<template>
    <div class="result-box">
        <div class="search-key">
            <input type="text" v-model="secondField" @keyup.enter="secondSearch" placeholder="在此输入  题名/责任者/出版地/出版社/出版年/主题词  回车进行二次检索">
        </div>
        <div class="filters">
            <a href="javascript:" v-for="(item,index) in filters" :key="index+Math.random()">{{item.title}}：{{item.value}} <a-icon type="close" @click="deleteFilter(index,item.type,item.value)" /></a>
        </div>
        <div class="result-info">
            <span>共匹配到<b>{{rowCount}}</b>条数据</span>
            <div class="sort">
                <!-- // 无:'' , 升序:'0' , 降序:'1' -->
                <span v-if="!disableSortScore" @click="onSortChange('score')">相关度 <em v-if="sort.field==='score'">{{sort.order === "asc"?'↑':'↓'}}</em></span>
                <!-- // 无:'' , 升序:'0' , 降序:'1' -->
                <span @click="onSortChange('title')">题名 <em v-if="sort.field==='title'">{{sort.order === "asc"?'↑':'↓'}}</em></span>
                <!-- // 无:'' , 升序:'0' , 降序:'1' -->
                <span @click="onSortChange('person')">责任者 <em v-if="sort.field==='person'">{{sort.order === "asc"?'↑':'↓'}}</em></span>
            </div>
        </div>
        <div class="result-info">
            <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange"><strong class="out-put">全选</strong></a-checkbox>
            <div class="sort hand" @click="download"><strong class="out-put">导出</strong></div>
        </div>
        <div class="result-list">
            <ul v-if="resultData&&resultData.length>0">
                <a-checkbox-group v-model="checkedList" @change="onChange">
                    <li v-for="(item,index) in resultData" :key="index">
                        <a-checkbox class="img-box" :value="item"></a-checkbox>
                        <!-- <router-link :to="{name: 'instanceDetail', query: {uri: item.uri)}}" target="_blank">
                            <img :src="imagePath(item.shelfs)" alt="">
                        </router-link> -->
                        <div @click="goToInstanceDetail(item.uri)" style="cursor: pointer;">
                            <!-- <img :src="imagePath(item.shelfs)" alt=""> -->
                            <PDFImage v-if="pdfPath(item.shelfs)" style="width: 100px; margin: 0 20px 20px 0;" :src="pdfPath(item.shelfs)" fixedWidth />
                            <img v-else style="width: 100px;" src="demo.png" alt="">
                        </div>
                        <div class="info">
                            <!-- <router-link :to="{name: 'instanceDetail', query: {uri: item.uri}}" target="_blank"><h4 v-html="item.title"></h4></router-link> -->
                            <div @click="goToInstanceDetail(item.uri)"><h4 v-html="item.title"></h4></div>
                            <p v-if="item.personInfoList&&item.personInfoList.length>0">
                                <span>责任者：</span>
                                <span v-for="(sub_item, sub_index) in item.personInfoList" :key="sub_index+'1'" v-show="sub_item.personUri">
                                    <span v-if="sub_item.personUri.indexOf('/mgts/')>-1" style="color: #4c4c4c" v-html="sub_item.personName"></span>
                                    <span v-else @click="toContributionPerson(sub_item.personUri)" style="color: #4c4c4c; border-bottom: 1px solid #000; text-decoration:none" class="hand " v-html="sub_item.personName"></span>
                                    <span v-if="sub_item.personRole" style="color: #4c4c4c">({{sub_item.personRole}})&nbsp;</span>
                                    <span v-else style="color: #4c4c4c">&nbsp;</span>
                                </span>
                            </p>
                            <p v-if="item.page"><span>页<i class="emp"/>码：</span>{{item.page}}</p>
                            <p v-if="item.dimensions"><span>尺<i class="emp"/>寸：</span>{{item.dimensions}}</p>
                            <p v-if="item.provision"><span>出<i class="emp"/>版：</span><span style="color: #4c4c4c" v-html="item.provision"></span></p>
                            <!-- <br><br> -->
                        </div>
                        <router-link class="more_version" :to="{name: 'moreVersion', query: {uri: item.workUri}}" target="_blank">更多版本信息 ></router-link>
                    </li>
                </a-checkbox-group>
            </ul>
        </div>
    </div>
</template>

<script>
    import PDFImage from '../../components/PDFImage.vue';
    export default {
        props: {
            resultData: { type: Array }, //传入类型
            rowCount: { type: Number },
            filters: { type: Array },
            sort: { type: Object, required: true },
            disableSortScore: { type: Boolean }
        },
        components: { PDFImage },
        data(){
            return{
                secondField: '',
                indeterminate: false,
                checkAll: false,
                checkedList: []
            }
        },

        created() {
           
        },

        computed: {
            imagePath() {
                return function(shelfs) {
                    let path = ""
                    if(shelfs&&shelfs.length>0) {
                        for (let i = 0; i < shelfs.length; i++) {
                            if(shelfs[i].cover) {
                                path = "//jdts.library.sh.cn/cover/" + shelfs[i].cover
                                break
                            }
                        }
                        if(path) {
                            return path
                        } else {
                            return "demo.png"
                        }
                    } else {
                        return "demo.png"
                    }
                }
            }
        },

        methods: {
            pdfPath(shelfs) {
                if(shelfs && shelfs.length > 0) {
                    for (let i = 0; i < shelfs.length; i++) {
                        if(shelfs[i].identifier) {
                            return `https://dhapi.library.sh.cn/service_pdf/pdf/mgts/cover?callNo=${shelfs[i].identifier}`
                        }
                    }
                }
                return null;
            },
            goToInstanceDetail(uri) {
                let path = this.$router.resolve({
                    path:"instanceDetail",
                    query: {uri: uri,token: sessionStorage.getItem('token')}
                })
                window.open(path.href,"_blank")
            },
            onChange(checkedValues) {
                this.checkedList = checkedValues
                this.indeterminate = !!this.checkedList.length && this.checkedList.length < this.resultData.length;
                this.checkAll = this.checkedList.length === this.resultData.length;
            },

            onCheckAllChange(e) {
                Object.assign(this, {
                    checkedList: e.target.checked ? this.resultData : [],
                    indeterminate: false,
                    checkAll: e.target.checked,
                });
            },

            // JSON转CSV-START
            setDataConver: function(obj) {
                var bw = this.browser();
                if(bw['ie'] < 9) return; // IE9以下的
                var data = obj['data'],
                    ShowLabel = typeof obj['showLabel'] === 'undefined' ? true : obj['showLabel'],
                    fileName = (obj['fileName'] || 'UserExport') + '.csv',
                    columns = obj['columns'] || {
                        title: [],
                        key: [],
                        formatter: undefined
                    };
                ShowLabel = typeof ShowLabel === 'undefined' ? true : ShowLabel;
                var row = "", CSV = '', key;
                // 如果要现实表头文字
                if (ShowLabel) {
                    // 如果有传入自定义的表头文字
                    if (columns.title.length) {
                        columns.title.map(function(n) {
                            row += n + ',';
                        });
                    } else {
                        // 如果没有，就直接取数据第一条的对象的属性
                        for (key in data[0]) row += key + ',';
                    }
                    row = row.slice(0, -1); // 删除最后一个,号，即a,b, => a,b
                    CSV += row + '\r\n'; // 添加换行符号
                }
                // 具体的数据处理
                data.map(function(n) {
                    row = '';
                    // 如果存在自定义key值
                    if (columns.key.length) {
                        columns.key.map(function(m) {
                            row += '"' + (typeof columns.formatter === 'function' ? columns.formatter(m, n[m]) || n[m] : n[m]) + '",';
                        });
                    } else {
                        for (key in n) {
                            row += '"' + (typeof columns.formatter === 'function' ? columns.formatter(key, n[key]) || n[key] : n[key]) + '",';
                        }
                    }
                    row.slice(0, row.length - 1); // 删除最后一个,
                    CSV += row + '\r\n'; // 添加换行符号
                });
                if(!CSV) return;
                this.SaveAs(fileName, CSV);
            },

            SaveAs: function(fileName, csvData) {
                var bw = this.browser();
                if(!bw['edge'] || !bw['ie']) {
                    var alink = document.createElement("a");
                    alink.id = "linkDwnldLink";
                    alink.href = this.getDownloadUrl(csvData);
                    document.body.appendChild(alink);
                    var linkDom = document.getElementById('linkDwnldLink');
                    linkDom.setAttribute('download', fileName);
                    linkDom.click();
                    document.body.removeChild(linkDom);
                }
                else if(bw['ie'] >= 10 || bw['edge'] == 'edge') {
                    var _utf = "\uFEFF";
                    var _csvData = new Blob([_utf + csvData], {
                        type: 'text/csv'
                    });
                    navigator.msSaveBlob(_csvData, fileName);
                }
                else {
                    var oWin = window.top.open("about:blank", "_blank");
                    oWin.document.write('sep=,\r\n' + csvData);
                    oWin.document.close();
                    oWin.document.execCommand('SaveAs', true, fileName);
                    oWin.close();
                }
            },
            
            getDownloadUrl: function(csvData) {
                var _utf = "\uFEFF"; // 为了使Excel以utf-8的编码模式，同时也是解决中文乱码的问题
                if (window.Blob && window.URL && window.URL.createObjectURL) {
                    csvData = new Blob([_utf + csvData], {
                        type: 'text/csv'
                    });
                    return URL.createObjectURL(csvData);
                }
                // return 'data:attachment/csv;charset=utf-8,' + _utf + encodeURIComponent(csvData);
            },

            browser: function() {
                var Sys = {};
                var ua = navigator.userAgent.toLowerCase();
                var s;
                (s = ua.indexOf('edge') !== - 1 ? Sys.edge = 'edge' : ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1]:
                    (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
                    (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                    (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                    (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                    (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
                return Sys;
            },
            // JSON转CSV-END

            download() {
                if(this.checkedList.length<=0) {
                    this.$message.error('请至少选中一条数据进行导出');
                } else {
                    this.checkedList.forEach(element => {
                        let personJoint = ''
                        if(element.personInfoList.length>0) {
                            element.personInfoList.forEach(e => {
                                if(e.personRole) {
                                    personJoint += e.personName + '（' + e.personRole + '）' + '；'
                                } else {
                                    personJoint += e.personName + '；'
                                }
                            });
                        }
                        // 去除html标签
                        element._title = element.title.replace(/<.*?>/ig,"")
                        element._personJoint = personJoint.replace(/<.*?>/ig,"")
                        element._page = element.page.replace(/<.*?>/ig,"")
                        element._dimensions = element.dimensions.replace(/<.*?>/ig,"")
                        element._provision = element.provision.replace(/<.*?>/ig,"")
                        
                    });
                    this.setDataConver({
                        data: this.checkedList,
                        fileName: 'data',
                        columns: {
                            title: ['题名','责任者','页码','尺寸','出版'],
                            key: ['_title','_personJoint','_page','_dimensions','_provision'],
                        },
                    })
                    // const url = this.genUrl(JSON.stringify(this.checkedList,"","\t")); // 已格式化(多行json)
                    // const a = document.createElement('a');
                    // a.href = url;
                    // a.download = "data.json";
                    // a.click();
                    // window.URL.revokeObjectURL(url);
                }
            },

            genUrl(encoded) {
                const dataBlob = new Blob([`\ufeff${encoded}`], {type:'text/plain;charset=utf-8'}); // 返回的格式
                return window.URL.createObjectURL(dataBlob);
            },

            addFilter(type,title,value){
                this.$parent.$parent.filters.push({type,title,value})
            },

            deleteFilter(index,type,value){
                if(type==='freetext') {
                    this.$parent.$parent.freetext = ''
                    this.$parent.$parent.$refs.Search.freetext = ''
                }
                if(type==='secondField') {
                    for (let i = 0; i < this.$parent.$parent.secondList.length; i++) {
                        if(this.$parent.$parent.secondList[i] == this.$parent.$parent.filters[index].value) {
                            this.$parent.$parent.secondList.splice(i, 1);
                        }
                    }
                    this.$parent.$parent.secondCdtn = this.$parent.$parent.secondList.join(" ")
                }
                if(type==='selectedKeys') {
                    this.$parent.$parent.selectedKeys = []
                }
                // params
                if(type==='all') {
                    this.$parent.$parent.params.all = ''
                }
                if(type==='title') {
                    this.$parent.$parent.params.title = ''
                }
                if(type==='person') {
                    this.$parent.$parent.params.person = ''
                }
                if(type==='place') {
                    this.$parent.$parent.params.place = ''
                }
                if(type==='publisher') {
                    this.$parent.$parent.params.publisher = ''
                }
                if(type==='theme') {
                    this.$parent.$parent.params.theme = ''
                }
                if(type==='publication') {
                    this.$parent.$parent.params.publication = ''
                }
                if(type==='start') {
                    this.$parent.$parent.params.start = ''
                }
                if(type==='end') {
                    this.$parent.$parent.params.end = ''
                }
                // facet
                if(type==='facetYear') {
                    this.$parent.$parent.facetYear = ''
                    for (let i = 0; i < this.$parent.$parent.facetYearFilterList.length; i++) {
                        if(this.$parent.$parent.facetYearFilterList[i]==value) {
                            this.$parent.$parent.facetYearFilterList.splice(i,1)
                        }
                    }
                    this.$parent.$parent.facetYearFilterList.forEach(element => {
                        this.$parent.$parent.facetYear += element + ' '
                    });
                }
                if(type==='facetPlace') {
                    this.$parent.$parent.facetPlace = ''
                    for (let i = 0; i < this.$parent.$parent.facetPlaceFilterList.length; i++) {
                        if(this.$parent.$parent.facetPlaceFilterList[i]==value) {
                            this.$parent.$parent.facetPlaceFilterList.splice(i,1)
                        }
                    }
                    this.$parent.$parent.facetPlaceFilterList.forEach(element => {
                        this.$parent.$parent.facetPlace += element + ' '
                    });
                }
                if(type==='facetPublisher') {
                    this.$parent.$parent.facetPublisher = ''
                    for (let i = 0; i < this.$parent.$parent.facetPublisherFilterList.length; i++) {
                        if(this.$parent.$parent.facetPublisherFilterList[i]==value) {
                            this.$parent.$parent.facetPublisherFilterList.splice(i,1)
                        }
                    }
                    this.$parent.$parent.facetPublisherFilterList.forEach(element => {
                        this.$parent.$parent.facetPublisher += element + ' '
                    });
                }
                if(type==='facetClass') {
                    this.$parent.$parent.facetClass = ''
                    for (let i = 0; i < this.$parent.$parent.facetClassFilterList.length; i++) {
                        if(this.$parent.$parent.facetClassFilterList[i]==value) {
                            this.$parent.$parent.facetClassFilterList.splice(i,1)
                        }
                    }
                    this.$parent.$parent.facetClassFilterList.forEach(element => {
                        this.$parent.$parent.facetClass += element + ' '
                    });
                }
                if(type==='facetPerson') {
                    this.$parent.$parent.facetPerson = ''
                    for (let i = 0; i < this.$parent.$parent.facetPersonFilterList.length; i++) {
                        if(this.$parent.$parent.facetPersonFilterList[i]==value) {
                            this.$parent.$parent.facetPersonFilterList.splice(i,1)
                        }
                    }
                    this.$parent.$parent.facetPersonFilterList.forEach(element => {
                        this.$parent.$parent.facetPerson += element + ' '
                    });
                }
                if(type==='facetKeyword') {
                    this.$parent.$parent.facetKeyword = ''
                    for (let i = 0; i < this.$parent.$parent.facetKeywordFilterList.length; i++) {
                        if(this.$parent.$parent.facetKeywordFilterList[i]==value) {
                            this.$parent.$parent.facetKeywordFilterList.splice(i,1)
                        }
                    }
                    this.$parent.$parent.facetKeywordFilterList.forEach(element => {
                        this.$parent.$parent.facetKeyword += element + ' '
                    });
                }
                if(type==='facetPdfCount') {
                    value = value=="内网有" ? "1" : value=="外网有" ? "0" : "其他"; 
                    this.$parent.$parent.facetPdfCount = ''
                    for (let i = 0; i < this.$parent.$parent.facetPdfCountFilterList.length; i++) {
                        if(this.$parent.$parent.facetPdfCountFilterList[i]==value) {
                            this.$parent.$parent.facetPdfCountFilterList.splice(i,1)
                        }
                    }
                    this.$parent.$parent.facetPdfCountFilterList.forEach(element => {
                        this.$parent.$parent.facetPdfCount += element + ' '
                    });
                }
                this.$parent.$parent.filters.splice(index,1)
                this.$parent.$parent.pageth = 1
                this.$parent.$parent.checkKeywords()
                this.$parent.$parent.normalSearch()
            },

            // 跳转至该作者的详细信息 (人名规范库页面)
            toContributionPerson(uri){
                 window.open(uri, '_blank');
            },

            secondSearch() {
                if(this.secondField) {
                    this.addFilter('secondField','搜索字',this.secondField)
                    this.$parent.$parent.secondList.push(this.secondField)
                    this.$parent.$parent.secondCdtn = this.$parent.$parent.secondList.join(" ")
                    this.$parent.$parent.pageth = 1
                    this.$parent.$parent.secondSearch()
                    // 查完再清空
                    this.secondField = ''
                }
            },

            onSortChange(field) {
                const { field: _field, order } = this.$props.sort;
                let newSort;
                if (field === _field) {
                    newSort = { field, order: order === "asc" ? "desc" : "asc" };
                } else {
                    newSort = { field, order: "asc" };
                }
                this.$emit("update:sort", newSort);
                this.$emit("sortChange");
            }

        },

        watch:{
            resultData (newVal, oldVal) {
                this.indeterminate = false
                this.checkAll = false
                this.checkedList = []
            },
        },
    }
</script>

<style lang="less" scoped>
    .more_version {
        font-size: 1.1rem;
    }
    .ant-checkbox-group {
        width: 100%;    
    }
    .img-box {
        margin-right: 10px;
    }
    .emp{
        padding: 8px;
    }
    .out-put{
        color: #965248;
        font-size: 1.2rem;
        padding: 0 5px;
    }
    .hand{
        cursor: pointer;
    }
    .result-box{
        font-size: 1rem;
    }
    .filters{
        margin: 20px 0 0 0;
        a{
            display: inline-block;
            border: 1px solid #126e82;
            height: 30px;
            vertical-align: top;
            box-sizing: border-box;
            line-height: 28px;
            border-radius: 15px;
            padding: 0 15px;
            margin-right: 10px;
            margin-bottom: 10px;
            color: #666;
        }
    }
    .result-list{
        margin-top: 10px;
        padding: 0 10px;
        li{
            list-style: none;
            display: flex;
            justify-content: space-between;
            padding: 20px 0;
            border-bottom: 1px solid #ddd;
            img{
                width: 100px;
                height: auto;
                cursor: pointer;
                margin-right: 20px;
            }
            a{
                align-self: flex-end;
                color: #4c4c4c;
            }
            .info{
                flex-grow: 1;
                margin-right: 20px;
                h4{
                    cursor: pointer;
                    font-size: 1.2rem;
                    color: #126e82;
                    line-height: 1.5;
                    margin-bottom: 10px;
                    font-weight: bold;
                }
                p{
                    margin: 0;
                    padding: 0;
                    line-height: 1.7;
                    color: #4c4c4c;
                    font-size: 1.1rem;
                    span{
                        color: #666;
                    }
                }
            }
        }
    }
    .result-info{
        border: 1px solid #ddd;
        display: flex;
        border-left: none;
        border-right: none;
        height: 32px;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        padding: 0 10px;
        .sort{
            span{
                color: #126e82;
                margin-left: 20px;
                cursor: pointer;
                em{
                    font-size: 18px;
                    font-style: normal;
                }
            }
        }
        span{
            line-height: 32px;
            color: #bbb;
            b{
                color: #126e82;
                font-size: 1.4rem;
                padding: 0 5px;
            }
        }
    }
    .search-key{
        input{
            width: 100%;
            height: 32px;
            border: 1px solid #126e82;
            border-radius: 16px;
            font-size: 1.1rem;
            display: block;
            box-sizing: border-box;
            padding-left: 10px;
        }
    }
</style>
